package com.katze.common.socket.server;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;

import java.net.Socket;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

public class SocketServerManager {
    private static final Logger log = LoggerFactory.getLogger(SocketServerManager.class);

    private static final ThreadPoolExecutor executor = new ThreadPoolExecutor(1, Integer.MAX_VALUE, 3, TimeUnit.MINUTES,
            new LinkedBlockingQueue<>(), new CustomizableThreadFactory("SocketServerPool-"));

    private static final Map<Integer, SocketServerThread> threads = new ConcurrentHashMap<>();

    public void initialization(int port, Function<Socket, Runnable> runnable) {
        threads.computeIfAbsent(port, (k) -> new SocketServerThread(k, sk-> executor.execute(runnable.apply(sk)))).start();
        log.info("通讯服务{}端口启动成功", port);
    }

    public void destroy() throws Exception {
        while (executor.getQueue().size() > 0) {
            log.info("剩余{}个通讯请求尚未处理", executor.getQueue().size());
            TimeUnit.SECONDS.sleep(1);
        }
    }

    public void close(int port) {
        threads.remove(port).exit();
    }
}
